<?php

$sql = "SELECT * FROM `questions` as q,`categories` as c WHERE q.cat_id=c.cat_id ";

if(!isset($_SESSION['q_count'])){
	$_SESSION['q_count'] = 20;
}

if(!isset($_SESSION['old_limit'])){
	$_SESSION['old_limit'] = 0;
}
if(!isset($_SESSION['m_limit'])){
	$_SESSION['m_limit'] = 20;
} else if (isset($_GET['limit'])){
	$_SESSION['m_limit'] = $_GET['limit'];
}

if (isset($_GET['page'])) {
	$_SESSION['old_limit'] = ($_GET['page']-1)*$_SESSION['m_limit'];
}

if(isset($_GET['category']) && $_GET['category'] != "all"){
	$_SESSION['selected_cat'] = $_GET['category'];
	$sql .= " AND q.cat_id = ".$_SESSION['selected_cat'];
}
else if ($_GET['category'] == "all"){
	$_SESSION['selected_cat'] = null;
}
else if ($_SESSION['selected_cat'] != null){
	$sql .= " AND q.cat_id = ".$_SESSION['selected_cat'];
}
//ffffff
if(isset($_GET['faculty']) && $_GET['faculty'] != "all"){
	$_SESSION['selected_f'] = $_GET['faculty'];
	$sql .= " AND c.faculty_ids LIKE '%".$_SESSION['selected_f']."%'";
}
else if ($_GET['faculty'] == "all"){
	$_SESSION['selected_f'] = null;
}
else if ($_SESSION['selected_f'] != null){
	$sql .= " AND c.faculty_ids in (".$_SESSION['selected_f'].")";
}
//f end
if(isset($_GET['complexity']) && $_GET['complexity'] != "Any"){
	$_SESSION['selected_comp'] = $_GET['complexity'];
	$sql .= " AND q.q_complexity = ".$_SESSION['selected_comp'];
}
else if ($_GET['complexity'] == "Any"){
	$_SESSION['selected_comp'] = null;
}
else if ($_SESSION['selected_comp'] != null){
	$sql .= " AND q.q_complexity = ".$_SESSION['selected_comp'];
}

if(isset($_GET['search'])){
	$_SESSION['search_q'] = $_GET['search'];
	$sql .= " AND q.q_title LIKE '%".$_SESSION['search_q']."%'";
}
//s end

if (isset($_GET['sortby'])){
	$_SESSION['sortby_c'] = $_GET['sortby'];
	$sql .= " ORDER BY ".$_SESSION['sortby_c'];
} else {
	$_SESSION['sortby_c'] = "q.q_id";
	$sql.=" ORDER BY ".$_SESSION['sortby_c'];
}

if(isset($_GET['step'])){
	$_SESSION['m_step'] = $_GET['step'];
	if ($_SESSION['old_limit'] + $_SESSION['m_step'] >= 0 && $_SESSION['old_limit'] + $_SESSION['m_step']<$_SESSION['q_count']) {
		$_SESSION['old_limit'] += $_SESSION['m_step'];
	}
	if ($_SESSION['old_limit'] + $_SESSION['m_step'] < 0 ){
		$_SESSION['old_limit'] = 0;
	}
}

$t_sql=$sql;
if(isset($_GET['limit'])){
	$_SESSION['m_limit'] = $_GET['limit'];
	if($_SESSION['m_limit'] > $_SESSION['q_count']) {
		$_SESSION['old_limit'] = 0;
	}
	$sql.=" ASC LIMIT ".$_SESSION['old_limit'].", ".$_SESSION['m_limit'];
}
else if($_SESSION['new_limit'] != null){
	$sql.=" ASC LIMIT ".$_SESSION['old_limit'].", ".$_SESSION['m_limit'];
}
else{
	$sql.=" ASC LIMIT ".$_SESSION['old_limit'].", ".$_SESSION['m_limit'];
}

$result = mysql_query($sql);

?>